//  Copyright (c) 2010 Mahesh Sharma,Matt MacDonald
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.

package org.prx.prp.view;

import java.io.IOException;
import java.util.ArrayList;

import org.prx.prp.R;
import org.prx.prp.controller.EpisodeManager;
import org.prx.prp.controller.ImageCacheManager;
import org.prx.prp.controller.ProgramManager;
import org.prx.prp.model.Episode;
import org.prx.prp.model.Program;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ProgramInfoView extends PRXCustomActivity {
	protected static final int SYNC_SUCC = 0;
	protected static final int SYNC_FAILED = 1;
	Program program;
	ArrayList<Episode> episodes;
	private LayoutInflater mInflater;
	private Context mContext;
	private Handler handler = new Handler() {
		public void handleMessage(Message g) {
			switch (g.what) {
			case SYNC_SUCC:
				ImageView logo = (ImageView) findViewById(R.id.program_logo);
				if (bitmap == null)
					logo.setImageResource(R.drawable.icon);
				else
					logo.setImageBitmap(bitmap);
				episodesList.setAdapter(new EpisodeListAdapter(mContext,
						episodes));
				episodesList.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						Intent intent = new Intent(mContext,
								EpisodeDetailsView.class);
						Bundle bundle = episodes.get(position - 1).getBundle();
						bundle.putString("program_name", program.getTitle());
						bundle.putString("PIURL", program.getImageUrl());
						intent.putExtras(bundle);
						startActivity(intent);
					}
				});

				break;
			case SYNC_FAILED:
				Toast msg = Toast.makeText(mContext, "Connection error",
						Toast.LENGTH_LONG);
				msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2,
						msg.getYOffset() / 2);
				msg.show();
				break;
			}
		}
	};
	private ListView episodesList;
	Bitmap bitmap;

	private void doUpdate() {
		episodes = EpisodeManager.findAllByPrograms(program.getProgramId());
		String imageURL = program.getImageUrl();
		if (!imageURL.equals("")) {
			try {
				bitmap = ImageCacheManager.getInstance().getBitmapFromURL(imageURL,
						0);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				bitmap = null;
			}
		}
		if (episodes != null && episodes.size() > 0) {
			handler.sendEmptyMessage(SYNC_SUCC);

		} else

			handler.sendEmptyMessage(SYNC_FAILED);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.program_info_view);
		mContext = this;
		final int programID = this.getIntent().getExtras().getInt("PROGRAM_ID");
		mInflater = LayoutInflater.from(this);
		final ImageButton imageButton = (ImageButton) findViewById(R.id.program_favorite_button);
		if (ProgramManager.isFavorite(programID))
			imageButton.setImageResource(R.drawable.tab_favorites);
		else
			imageButton.setImageResource(R.drawable.tab_no_favorite);
		imageButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (ProgramManager.isFavorite(programID)) {
					ProgramManager.removeFavorite(programID);
					imageButton.setImageResource(R.drawable.tab_no_favorite);
				} else {
					ProgramManager.addFavorite(programID);
					imageButton.setImageResource(R.drawable.tab_favorites);
				}
			}
		});
		View header = mInflater.inflate(org.prx.prp.R.layout.header, null);
		TextView headerText = (TextView) header.findViewById(R.id.header_text);
		TextView programName = (TextView) findViewById(R.id.program_name);
		TextView programDescription = (TextView) findViewById(R.id.program_description);
		headerText.setText("Episodes");
		program = ProgramManager.findById(programID);

		episodesList = (ListView) findViewById(R.id.program_episode_list);
		episodesList.addHeaderView(header);
		programName.setText(program.getTitle());
		if (program.getDescription().length() > 150)
			programDescription.setText(program.getDescription().substring(0,
					150)
					+ "...");
		else
			programDescription.setText(program.getDescription());
		Thread thread = new Thread(new Runnable() {
			public void run() {
				doUpdate();
			}
		});
		thread.start();
		Toast msg = Toast.makeText(mContext, "Getting program episodes...",
				Toast.LENGTH_LONG);
		msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2,
				msg.getYOffset() / 2);
		msg.show();
	}

	class EpisodeListAdapter extends BaseAdapter {
		ArrayList<Episode> episodes;
		Context mContext;
		private LayoutInflater mInflater;

		public EpisodeListAdapter(Context context, ArrayList<Episode> episodes) {
			this.mContext = context;
			this.episodes = episodes;
			mInflater = LayoutInflater.from(context);

		}

		public int getCount() {
			return episodes.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View test = null;
			final Episode e = episodes.get(position);
			test = mInflater.inflate(R.layout.program_episode_item, null);
			TextView textView = (TextView) test.findViewById(R.id.episode_title);
			textView.setText(e.getTitle());
			TextView t1 = (TextView) test.findViewById(R.id.published_time);
			t1.setText("Published on " + e.getPublished().substring(0, 10));
			return test;
		}
	}
}